package com.guoqi.keepsign.album

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import com.guoqi.keepsign.R
import com.guoqi.keepsign.base.ImageInfo
import com.guoqi.keepsign.previewlibrary.GPreviewActivity
import com.guoqi.keepsign.previewlibrary.GPreviewActivity.ACTION_EXIT
import kotlinx.android.synthetic.main.ui_album.*
import java.util.*


class AlbumUI : AppCompatActivity() {

    private var imageList = ArrayList<ImageInfo>()
    private var albumAdapter: AlbumAdapter? = null

    companion object {
        var backPosition = 0
    }

    private var brExit = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            context?.let {
                intent?.let {
                    backPosition = it.getIntExtra(GPreviewActivity.POSITION, 0)
                    rvAlbum.smoothScrollToPosition(backPosition)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.ui_album)

        tv_title.text = intent.getStringExtra("title") ?: ""
        imageList = intent.getSerializableExtra("imageList") as ArrayList<ImageInfo>
        rvAlbum.layoutManager = GridLayoutManager(this, 2)
        albumAdapter = AlbumAdapter(this, imageList!!, rvAlbum.layoutManager as GridLayoutManager)
        rvAlbum.adapter = albumAdapter

        val filter = IntentFilter(ACTION_EXIT)
        LocalBroadcastManager.getInstance(this).registerReceiver(brExit, filter)

    }

    override fun onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(brExit)
        super.onDestroy()
    }
}